import 'translation.dart';

bool isItem(Map item, List<String> codes) {
  return codes
      .firstWhere((element) => item[element] != null, orElse: () => '')
      .isNotEmpty;
}

extension I18nObj on Map {
  // String zhCN;
  // String zhHK;
  // String viVN;
  // String enUS;
  // String koKR;
  // String jaJP;
  void putObj(String code, dynamic value) => this[code] = value;

  bool isItem(List<String> codes) {
    return codes
        .firstWhere((element) => this[element] != null, orElse: () => '')
        .isNotEmpty;
  }

  String warning(List<String> codes) {
    var body = '';
    for (var code in codes) {
      if (this[code] == null) body += '$code ';
    }
    return body;
  }

  Future checkfill(List<String> codes) async {
    final defaultCode = codes.first;
    if (this[defaultCode] is String) {
      await _checkFillText(defaultCode, this[defaultCode], codes);
    } else if (this[defaultCode] is List) {
      await _checkFillList(defaultCode, this[defaultCode], codes);
    }
  }

  Future _checkFillText(
      String defaultCode, String defaultValue, List<String> codes) async {
    for (var code in codes) {
      if (this[code] == null && defaultValue.isNotEmpty == true) {
        this[code] = await translation(defaultValue, defaultCode, code);
        print('翻译文本：${this[code]}');
      }
    }
  }

  Future _checkFillList(
      String defaultCode, List defaultList, List<String> codes) async {
    for (var code in codes) {
      List list = this[code] ?? [];
      if (defaultList.length != list.length) {
        for (var defaultValue in defaultList) {
          if (defaultList.indexOf(defaultValue) >= list.length) {
            final text = await translation(defaultValue, defaultCode, code);
            list.add(text);
            print('翻译文本：$text');
          }
        }
        this[code] = list;
      }
    }
  }
}
